package com.liuguang.framework.utils;

import android.util.Base64;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class SafeSignUtil {
    private static final String ALGORITHM = "RSA";
    private static final String ENCODING = "UTF-8";
    private static final String MAC_NAME = "HmacSHA1";
    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";

    public static String initMacKey() throws Exception {
        KeyGenerator.getInstance(MAC_NAME).generateKey();
        return null;
    }

    public static byte[] hexString2Bytes(String str) {
        int length = str.length() / 2;
        byte[] bArr = new byte[length];
        for (int i = 0; i < length; i++) {
            int i2 = i * 2;
            bArr[i] = Integer.valueOf(str.substring(i2, i2 + 2), 16).byteValue();
        }
        return bArr;
    }

    public static String ByteToHex(byte[] bArr) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < bArr.length; i++) {
            if (Integer.toHexString(bArr[i] & 255).length() == 1) {
                stringBuffer.append("0");
                stringBuffer.append(Integer.toHexString(bArr[i] & 255));
            } else {
                stringBuffer.append(Integer.toHexString(bArr[i] & 255));
            }
        }
        return stringBuffer.toString();
    }

    public static byte[] HmacSHA1Encrypt(String str, String str2) {
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(str2.getBytes("UTF-8"), MAC_NAME);
            Mac instance = Mac.getInstance(MAC_NAME);
            instance.init(secretKeySpec);
            return instance.doFinal(str.getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String sign(String str, String str2) {
        try {
            PrivateKey generatePrivate = KeyFactory.getInstance(ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(Base64.decode(str2, 0)));
            Signature instance = Signature.getInstance(SIGN_ALGORITHMS);
            instance.initSign(generatePrivate);
            instance.update(str.getBytes("UTF-8"));
            return Base64.encodeToString(instance.sign(), 0);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
